package com.njlime.sys.controller;

import com.njlime.core.base.controller.BaseController;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.helper.GlobalValue;
import com.njlime.core.helper.PageBean;
import com.njlime.core.sdk.wechat.WeChatUtil;
import com.njlime.core.sdk.wechat.open.OpenAccessToken;
import com.njlime.core.utils.StringUtil;
import com.njlime.core.web.validation.annotation.support.ValidateService;
import com.njlime.sys.entities.User;
import com.njlime.sys.security.util.UserUtils;
import com.njlime.sys.service.UserService;
import com.njlime.sys.util.NoteSendUtil;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * 用户控制器
 * Created by Dean on 2017-7-21.
 */
@Controller
@RequestMapping(value = "/sys/user")
public class UserController extends BaseController {

    @Resource
    private UserService userService;

    //-------------------控制器--------------------

    /**
     * 跳转热点管理页面
     * @return
     */
    @RequestMapping(value = "userManage")
    public ModelAndView infoManage(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/sys/terrace/account/index");
        return modelAndView;
    }

    //------------------接口-----------------

    /**
     * 用户列表
     * @return
     */
    @RequestMapping(value = "userList", method = RequestMethod.GET)
    @ResponseBody
    public String userList(HttpServletRequest request, User user, PageBean pageBean) {
        try {
            if (pageBean == null) {
                pageBean = new PageBean();
            }
            if(user == null){
                user = new User();
            }
            return toJsonListData(userService.list(pageBean, user));
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 全部用户
     * @return
     */
    @RequestMapping(value = "allUser", method = RequestMethod.GET)
    @ResponseBody
    public String allUser(HttpServletRequest request, User user) {
        try {
            PageBean pageBean = new PageBean();
            pageBean.setPageSize(Integer.MAX_VALUE);
            if(user == null){
                user = new User();
            }
            return toJsonListData(userService.list(pageBean, user));
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 用户新增
     * @return
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public String add(HttpServletRequest request, User user, Integer role_id) {
        try {
            user.setStatus(GlobalValue.AUDITED);
            ValidateService.valid(user);
            user.setCreator(UserUtils.getUser().getId());
            userService.addUser(user, role_id);
            return toJsonSuccessData();
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 用户信息
     * @return
     */
    @RequestMapping(value = "userInfo", method = RequestMethod.GET)
    @ResponseBody
    public String userInfo(HttpServletRequest request, Integer id) {
        try {
            Map<String,Object> map = userService.getById(id);
            map.put("uid", getLoginUser().getId());
            return toJsonSuccessData(map);
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 用户编辑
     * @return
     */
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    @ResponseBody
    public String edit(HttpServletRequest request, User user, Integer role_id) {
        try {
            userService.editUser(user, role_id);
            return toJsonSuccessData();
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 发送手机短信码
     */
    @ResponseBody
    @RequestMapping(value = "sendVerifyCode")
    public String sendVerifyCode(HttpServletRequest request, String mobile) {
        logger.info("/noteCodeSend");
        try {
            Long noteCodeTime = (Long) request.getSession().getAttribute("noteCodeTime");
            Long timeNow = (new Date()).getTime();
            if (noteCodeTime != null && ((timeNow - noteCodeTime) / 1000) < NoteSendUtil.SEND_PERIOD) {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "请勿在60秒内重复发送短信");
            }
            String noteCode = NoteSendUtil.getRandNum(6);
            logger.info(mobile + ":" + noteCode);
            if (NoteSendUtil.verifyNote(mobile, noteCode)) {
                request.getSession().setAttribute("noteCodeMobile", mobile);
                request.getSession().setAttribute("noteCode", noteCode);
                request.getSession().setAttribute("noteCodeTime", (new Date()).getTime());
                return toJsonSuccessData();
            } else {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "请验证您的手机是否正确");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "发送验证码出错，请稍后重试");
        }
    }

    /**
     * 修改密码
     * @return
     */
    @RequestMapping(value = "changePwd", method = RequestMethod.POST)
    @ResponseBody
    public String changePwd(HttpServletRequest request, User user, String verifyCode) {
        try {
            String noteCode = (String) request.getSession().getAttribute("noteCode");
            String noteCodeMobile = (String) request.getSession().getAttribute("noteCodeMobile");
            if (StringUtil.isEmpty(noteCode)) {
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "短信验证码错误");
            } else {
                if (noteCode.equals(verifyCode) && user.getMobile().equals(noteCodeMobile)) {
                    userService.editUser(user, null);
                    return toJsonSuccessData();
                } else {
                    return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "短信验证码错误");
                }
            }
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }


    /**
     * 用户删除
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(HttpServletRequest request,String ids) {
        try {
            String[] idArray = ids.split(",");
            userService.deleteUser(idArray);
            return toJsonSuccessData();
        } catch (Exception e) {
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 绑定微信
     * @param request
     * @return
     */
    @RequestMapping(value = "bindWx", method = RequestMethod.GET)
    public ModelAndView bindWx(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView("/sys/terrace/config/myAccount");
        try{
            String code = WebUtils.getCleanParam(request, "code");
            OpenAccessToken openAccessToken = WeChatUtil.getOpenAccessToken(WeChatUtil.OPEN_APP_ID, WeChatUtil.OPEN_APP_SECRET, code);
            String openid = openAccessToken.getOpenid();
            User user = new User();
            user.setId(UserUtils.getUser().getId());
            user.setOpenid(openid);
            userService.editUser(user, null);
            modelAndView.addObject("user", userService.getById(UserUtils.getUser().getId()));
            modelAndView.addObject("msg", "绑定成功");
        }catch (Exception e){
            modelAndView.addObject("msg","绑定微信失败");
        }
        return modelAndView;
    }

}
